package com.sky.task;

import com.sky.constant.MessageConstant;
import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;

@Component
@Slf4j
public class AutoTask {
	
	private final OrderMapper orderMapper;
	
	private final StringRedisTemplate redisTemplate;
	
	public AutoTask(OrderMapper orderMapper, StringRedisTemplate redisTemplate) {
		this.orderMapper = orderMapper;
		this.redisTemplate = redisTemplate;
	}
	
	/**
	 * 每分钟检查一次超时订单, 未支付时间超过十五分钟的订单改为取消
	 */
	@Scheduled(cron = "0 0/1 * * * ?")
	public void autoCancelOrder() {
		LocalDateTime CancelTime = LocalDateTime.now().plusMinutes(-15);
		List<Orders> orders = orderMapper.getByStatusAndTime(Orders.PAID, CancelTime);
		log.info("查询到超时订单{}条.", orders.size());
		orders.forEach(order -> {
			order.setStatus(Orders.CANCELLED);
			order.setCancelTime(CancelTime);
			order.setCancelReason(MessageConstant.PAYMENT_TIMEOUT);
			orderMapper.update(order);
		});
	}
	
	/**
	 * 每天凌晨1点检查派送中的订单, 改为已完成
	 */
	@Scheduled(cron = "0 0 1 1/1 * ?")
	public void autoCompleteOrder() {
		List<Orders> orders = orderMapper.getByStatusAndTime(Orders.DELIVERY_IN_PROGRESS, LocalDateTime.now());
		log.info("查询到派送中订单{}条.", orders.size());
		orders.forEach(order -> {
			order.setStatus(Orders.COMPLETED);
			orderMapper.update(order);
		});
	}
	
	/**
	 * 每周日0点清理redis缓存
	 */
	@Scheduled(cron = "0 0 00 ? * SUN")
	public void clean() {
		List<Object> cacheNames = redisTemplate.opsForHash().values("__cacheName");
		cacheNames.forEach(cacheName -> {
			Set<String> keys = redisTemplate.keys(cacheName + "::*");
			if (keys != null) {
				log.info("清理缓存: {}", cacheName);
				redisTemplate.delete(keys);
			}
		});
	}
}
